<?php
namespace frontend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\web\IdentityInterface;


class Group extends ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%group}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'describe'], 'trim'],
            [['title', 'describe'], 'required','message' => '{attribute}不能为空'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'describe' => '内容',
            'set_posts_id' => '发帖人id',
            'set_posts_name' => '发帖人',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'describe',
                'sort',
                'banner',
                'video',
            ],
            'create' => [
                'id',
                'title',
                'describe',
                'img',
                'set_posts_id',
                'set_posts_name'.
                'status',
                'create_time',
                'update_time',
            ],
            'update' => [
                '!id',
                'title',
                'describe',
                'img',
                'sort',
                'banner',
                'video',
                'admin_id',
                'admin_name'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
        ];
    }

    /**
     * 更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function saveInfo($scenario, $data, $id = 0){
        if (!in_array($scenario, ['create', 'update'])) {
            return false;
        }
        $t = static::getDb()->beginTransaction();
        try {
            if ($scenario == 'update') {
                $id = intval($id);
                if (!$id) {
                    return false;
                }
                $model           = static::findOne(['id' =>$id]);
                if(empty($model)) throw new Exception('不存在此用户');
                $model->scenario = 'update';
            } else {
                $model           = new self();
                $model->scenario = 'create';
            }
            $model->setAttributes($data, false);
            if (!$model->save()) {
                $t->rollBack();
                return $model;
            }
            $model->refresh();
            $t->commit();
            return $model->attributes['id'];
            //return $model;
        } catch (Exception $e) {
            $t->rollback();
            return $e;
        }
    }

    /**
     * @inheritdoc
     */
    public static function selectFieldData($data = [],$field = '*')
    {
        $query = new \yii\db\Query();
        $query->select($field)->from('group');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data['group_cat_id'])){
            $query->andWhere(['group_cat_id' => $data['group_cat_id']]);
        }

        $command = $query->createCommand();
        $result = $command->queryAll();
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectLimitInfo($data = [],$field = '*',$page = 0,$pageSize = '')
    {
        $model = new \frontend\models\GroupMember();
        $query = new \yii\db\Query();
        $query->select([$field])->from('group');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'is_recommend' => SORT_DESC,
            'updated_at' => SORT_DESC,
        ]);
        if(!empty($data['group_cat_id'])){
            $query->andWhere(['group_cat_id' => $data['group_cat_id']]);
        }
        if(!empty($data['is_recommend'])){
            $query->andWhere(['is_recommend' => $data['is_recommend']]);
        }
        if(!empty($data['data'])){
            $query->andWhere(['like', 'name', $data['data']]);
        }
        if(!empty($pageSize)){
            $query->offset(($page - 1) * $pageSize)->limit($pageSize);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $result[$k]['member_num'] = count($model::selectFieldData(['group_id' => $v['id']],'`id`'));
            if(!empty($data['member_id'])){
                $rat = $model::findData(['group_id' => $v['id'],'member_id' => $data['member_id']],'`id`');
                if(empty($rat)){
                    $result[$k]['is_add'] = 'no';
                }else{
                    $result[$k]['is_add'] = 'yes';
                }
            }else{
                $result[$k]['is_add'] = 'no';
            }
        }
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function selectJoinInfo($data = [],$field = '*')
    {
        $model = new \frontend\models\GroupMember();
        $query = new \yii\db\Query();
        $query->select([$field])->from('group');
        $query->leftJoin('group_member g','`group`.`id` = `g`.`group_id`');
        $query->where(['`g`.`deleted_at`' => null]);
        $query->orderBy([
            '`group`.`created_at`' => SORT_DESC,
        ]);
        if(!empty($data['member_id'])){
            $query->andWhere(['member_id' => $data['member_id']]);
        }
        $command = $query->createCommand();
        $result = $command->queryAll();
        foreach ($result as $k => $v){
            $result[$k]['member_num'] = count($model::selectFieldData(['group_id' => $v['id']],'`id`'));
        }
        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function findInfo($data = [],$field = '*')
    {
        $model = new \frontend\models\GroupMember();
        $query = new \yii\db\Query();
        $query->select([$field])->from('group');
        $query->where(['deleted_at' => null]);
        $query->orderBy([
            'created_at' => SORT_DESC,
        ]);
        if(!empty($data['id'])){
            $query->andWhere(['id' => $data['id']]);
        }
        if(!empty($data['is_recommend'])){
            $query->andWhere(['is_recommend' => $data['is_recommend']]);
        }
        $command = $query->createCommand();
        $result = $command->queryOne();
        $result['member_num'] = count($model::selectFieldData(['group_id' => $result['id']],'`id`'));
        $result['member'] = $model::selectJoinData(['group_id' => $result['id']],'`m`.`username`,`m`.`head_img`');
        if(!empty($data['member_id'])){
            $rat = $model::findData(['group_id' => $result['id'],'member_id' => $data['member_id']],'`id`');
            if(empty($rat)){
                $result['is_add'] = 'no';
            }else{
                $result['is_add'] = 'yes';
            }
        }else{
            $result['is_add'] = 'no';
        }
        return $result;
    }

}
